<template>
  <div class="yuebanmao-netdisk-container">
    <!-- 添加星空背景元素 -->
    <div class="floating-element element-1"></div>
    <div class="bright-star star1"></div>
    <div class="bright-star star2"></div>
    <div class="bright-star star3"></div>
    <div class="bright-star star4"></div>
    <div class="bright-star star5"></div>
    
    <!-- 添加彗星元素 -->
    <div class="comet comet1">
      <div class="comet-body">
        <div class="comet-tail"></div>
      </div>
    </div>
    <div class="comet comet2">
      <div class="comet-body">
        <div class="comet-tail"></div>
      </div>
    </div>
    <div class="comet comet3">
      <div class="comet-body">
        <div class="comet-tail"></div>
      </div>
    </div>

    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <span class="logo-icon"><i class="fa-solid fa-cloud-moon"></i></span>
        <span class="logo-text">月半猫网盘</span>
      </div>

      <div class="search-bar">
        <FontAwesomeIcon :icon="['fas', 'search']" />
        <input
            type="text"
            v-model="searchQuery"
            placeholder="搜索文件"
            @keyup.enter="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>

      <div class="user-info">
        <img :src="userStore.userInfo.avatar" alt="用户头像" class="user-avatar" />
        <span class="user-name">{{ userStore.userInfo.name }}</span>
        <button @click="handleLogout" class="logout-btn">
          <FontAwesomeIcon :icon="['fas', 'sign-out-alt']" />
        </button>
      </div>
    </header>

    <div class="main-content">
      <!-- 左侧边栏 -->
      <DashboardSidebar 
        :user-info="userStore.userInfo" 
        :nav-menus="userStore.navMenus" 
        @menu-click="handleNavMenuClick"
      />

      <!-- 右侧内容区 -->
      <FileListView 
        :file-list="userStore.fileList" 
        @upload="handleUpload"
        @create-folder="handleCreateFolder"
        @file-click="handleFileClick"
        @delete-file="handleDeleteFile"
        @rename-file="handleRenameFile"
        @preview-file="handlePreviewFile"
        @share-file="handleShareFile"
        @refresh="refreshFileList"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import DashboardSidebar from './DashboardSidebar.vue';
import FileListView from './FileListView.vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { useUserStore, NavMenu, FileItem } from '@/stores/counter';

// 使用用户状态
const userStore = useUserStore();
const router = useRouter();

// 后端API基础URL
const BASE_URL = 'http://localhost:8080';

// 搜索查询
const searchQuery = ref('');

// 当前文件夹ID
const currentFolderId = ref(0);

// 组件挂载时加载数据
onMounted(async () => {
  // 获取用户信息
  await userStore.loadUserInfo();
  
  // 加载文件列表
  await refreshFileList();
});

// 刷新文件列表
const refreshFileList = async () => {
  await userStore.loadFileList(currentFolderId.value);
};

// 处理搜索
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    // 如果搜索框为空，则显示当前文件夹的所有文件
    await refreshFileList();
    return;
  }
  
  try {
    const response = await axios.get(
      `${BASE_URL}/file/search`,
      { 
        params: { keyword: searchQuery.value },
        headers: { 
          userid: localStorage.getItem('userid') || '', 
          token: localStorage.getItem('token') || '' 
        } 
      }
    );
    
    if (response.data.code === 1) {
      // 更新文件列表
      userStore.fileList = response.data.data.map((file: any) => ({
        id: file.id,
        type: file.type,
        name: file.name,
        size: file.size === 0 ? '-' : formatFileSize(file.size),
        time: new Date(file.modifiedTime).toLocaleString()
      }));
    }
  } catch (error) {
    console.error('搜索失败:', error);
  }
};

// 导航菜单切换
const handleNavMenuClick = (menu: NavMenu) => {
  userStore.navMenus.forEach((item) => {
    item.active = item.id === menu.id;
  });
  
  // 根据菜单ID执行不同操作
  if (menu.id === 1) { // 首页
    refreshFileList();
  } else if (menu.id === 2) { // 我的文件
    refreshFileList();
  } else if (menu.id === 7) { // 回收站
    loadRecycleBin();
  } else {
    // 其他菜单按文件类型筛选
    filterFilesByType(menu.text);
  }
};

// 加载回收站
const loadRecycleBin = async () => {
  try {
    const response = await axios.get(
      `${BASE_URL}/recycle/list`,
      { 
        headers: { 
          userid: localStorage.getItem('userid') || '', 
          token: localStorage.getItem('token') || '' 
        } 
      }
    );
    
    if (response.data.code === 1) {
      userStore.fileList = response.data.data.map((file: any) => ({
        id: file.id,
        type: file.type,
        name: file.name,
        size: file.size === 0 ? '-' : formatFileSize(file.size),
        time: new Date(file.modifiedTime).toLocaleString()
      }));
    }
  } catch (error) {
    console.error('加载回收站失败:', error);
  }
};

// 根据类型筛选文件
const filterFilesByType = async (type: string) => {
  try {
    const response = await axios.get(
      `${BASE_URL}/file/list`,
      { 
        params: { type: type.toLowerCase() },
        headers: { 
          userid: localStorage.getItem('userid') || '', 
          token: localStorage.getItem('token') || '' 
        } 
      }
    );
    
    if (response.data.code === 1) {
      userStore.fileList = response.data.data.map((file: any) => ({
        id: file.id,
        type: file.type,
        name: file.name,
        size: file.size === 0 ? '-' : formatFileSize(file.size),
        time: new Date(file.modifiedTime).toLocaleString()
      }));
    }
  } catch (error) {
    console.error('筛选文件失败:', error);
  }
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 文件操作处理函数
// 处理文件点击
const handleFileClick = (file: FileItem) => {
  if (file.type === 'folder') {
    // 如果是文件夹，进入该文件夹
    currentFolderId.value = file.id;
    refreshFileList();
  } else {
    // 如果是文件，预览该文件
    handlePreviewFile(file.id);
  }
};

// 处理上传
const handleUpload = () => {
  // 创建文件输入元素
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.multiple = true; // 允许多选
  
  // 监听文件选择事件
  fileInput.onchange = async (event) => {
    const target = event.target as HTMLInputElement;
    const files = target.files;
    
    if (!files || files.length === 0) return;
    
    // 创建FormData对象
    const formData = new FormData();
    
    // 添加文件夹ID
    formData.append('folderId', currentFolderId.value.toString());
    
    // 添加所有选择的文件
    for (let i = 0; i < files.length; i++) {
      formData.append('files', files[i]);
    }
    
    try {
      const response = await axios.post(
        `${BASE_URL}/file/upload`,
        formData,
        { 
          headers: { 
            'Content-Type': 'multipart/form-data',
            userid: localStorage.getItem('userid') || '', 
            token: localStorage.getItem('token') || '' 
          } 
        }
      );
      
      if (response.data.code === 1) {
        alert('文件上传成功');
        refreshFileList();
      } else {
        alert('文件上传失败: ' + response.data.msg);
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      alert('文件上传失败');
    }
  };
  
  // 触发文件选择对话框
  fileInput.click();
};

// 创建文件夹
const handleCreateFolder = async () => {
  const folderName = prompt('请输入文件夹名称');
  if (folderName) {
    try {
      const response = await axios.post(
        `${BASE_URL}/folder/create`,
        { name: folderName, parentId: currentFolderId.value },
        { 
          headers: { 
            userid: localStorage.getItem('userid') || '', 
            token: localStorage.getItem('token') || '' 
          } 
        }
      );
      
      if (response.data.code === 1) {
        alert('文件夹创建成功');
        refreshFileList();
      } else {
        alert('文件夹创建失败: ' + response.data.msg);
      }
    } catch (error) {
      console.error('文件夹创建失败:', error);
      alert('文件夹创建失败');
    }
  }
};

// 删除文件
const handleDeleteFile = async (fileId: number) => {
  if (confirm('确定要删除该文件吗？')) {
    try {
      const response = await axios.delete(
        `${BASE_URL}/file/delete/${fileId}`,
        { 
          headers: { 
            userid: localStorage.getItem('userid') || '', 
            token: localStorage.getItem('token') || '' 
          } 
        }
      );
      
      if (response.data.code === 1) {
        alert('文件删除成功');
        refreshFileList();
      } else {
        alert('文件删除失败: ' + response.data.msg);
      }
    } catch (error) {
      console.error('文件删除失败:', error);
      alert('文件删除失败');
    }
  }
};

// 重命名文件
const handleRenameFile = async (fileId: number) => {
  const newName = prompt('请输入新名称');
  if (newName) {
    try {
      const response = await axios.put(
        `${BASE_URL}/file/rename/${fileId}`,
        { name: newName },
        { 
          headers: { 
            userid: localStorage.getItem('userid') || '', 
            token: localStorage.getItem('token') || '' 
          } 
        }
      );
      
      if (response.data.code === 1) {
        alert('文件重命名成功');
        refreshFileList();
      } else {
        alert('文件重命名失败: ' + response.data.msg);
      }
    } catch (error) {
      console.error('文件重命名失败:', error);
      alert('文件重命名失败');
    }
  }
};

// 预览文件
const handlePreviewFile = async (fileId: number) => {
  try {
    const response = await axios.get(
      `${BASE_URL}/file/preview/${fileId}`,
      { 
        headers: { 
          userid: localStorage.getItem('userid') || '', 
          token: localStorage.getItem('token') || '' 
        } 
      }
    );
    
    if (response.data.code === 1) {
      // 根据返回的预览URL或内容处理预览逻辑
      window.open(response.data.data, '_blank');
    }
  } catch (error) {
    console.error('文件预览失败:', error);
    alert('文件预览失败');
  }
};

// 分享文件
const handleShareFile = async (fileId: number) => {
  const shareUserId = prompt('请输入分享对象的用户ID（0为公开分享）');
  if (shareUserId) {
    try {
      const response = await axios.post(
        `${BASE_URL}/file/share/${fileId}`,
        { userId: parseInt(shareUserId, 10) },
        { 
          headers: { 
            userid: localStorage.getItem('userid') || '', 
            token: localStorage.getItem('token') || '' 
          } 
        }
      );
      
      if (response.data.code === 1) {
        alert(`文件分享成功，分享链接: ${response.data.data}`);
      }
    } catch (error) {
      console.error('文件分享失败:', error);
      alert('文件分享失败');
    }
  }
};

// 注销登录
const handleLogout = () => {
  localStorage.removeItem('userid');
  localStorage.removeItem('token');
  router.push('/login_register');
};
</script>

<style scoped>
/* 重置样式 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 星空背景样式 */
.yuebanmao-netdisk-container {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #000000; /* 纯黑背景 */
  font-family: 'Helvetica Neue', Arial, sans-serif;
  color: #e0e0e0; /* 默认字体颜色 */
  overflow: hidden;
  box-shadow:
    inset 0 0 50px rgba(134, 3, 174, 0.15),
    inset 0 0 100px rgba(134, 3, 174, 0.1),
    0 0 80px rgba(134, 3, 174, 0.1);
  animation: borderGlow 8s infinite alternate;
}

/* 边缘发光动画 */
@keyframes borderGlow {
  0% {
    box-shadow:
      inset 0 0 50px rgba(134, 3, 174, 0.1),
      inset 0 0 100px rgba(134, 3, 174, 0.05),
      0 0 80px rgba(134, 3, 174, 0.05);
  }
  50% {
    box-shadow:
      inset 0 0 60px rgba(134, 3, 174, 0.15),
      inset 0 0 120px rgba(134, 3, 174, 0.1),
      0 0 100px rgba(134, 3, 174, 0.1);
  }
  100% {
    box-shadow:
      inset 0 0 50px rgba(134, 3, 174, 0.1),
      inset 0 0 100px rgba(134, 3, 174, 0.05),
      0 0 80px rgba(134, 3, 174, 0.05);
  }
}

/* 星空背景效果 */
.yuebanmao-netdisk-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 200%;
  height: 200%;
  background-image:
    radial-gradient(1px 1px at 25% 15%, rgba(255, 255, 255, 0.9), transparent),
    radial-gradient(1px 1px at 50% 40%, rgba(255, 255, 255, 0.8), transparent),
    radial-gradient(1.5px 1.5px at 15% 25%, rgba(255, 255, 255, 0.7), transparent),
    radial-gradient(1.5px 1.5px at 75% 55%, rgba(255, 255, 255, 0.9), transparent),
    radial-gradient(1px 1px at 35% 65%, rgba(255, 255, 255, 0.8), transparent),
    radial-gradient(1.5px 1.5px at 65% 10%, rgba(255, 255, 255, 0.9), transparent),
    radial-gradient(2px 2px at 85% 35%, rgba(255, 255, 255, 0.7), transparent),
    radial-gradient(1px 1px at 10% 85%, rgba(255, 255, 255, 0.8), transparent),
    radial-gradient(1.5px 1.5px at 50% 75%, rgba(255, 255, 255, 0.7), transparent),
    radial-gradient(2px 2px at 30% 90%, rgba(255, 255, 255, 0.8), transparent),
    radial-gradient(2.5px 2.5px at 85% 80%, rgba(255, 255, 255, 0.9), transparent);
  background-repeat: repeat;
  background-size: 500px 500px;
  opacity: 1;
  z-index: 0;
  animation: glowPulse 10s infinite alternate;
}

@keyframes glowPulse {
  0% {
    opacity: 0.7;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.7;
  }
}

/* 明亮的星星 */
.bright-star {
  position: absolute;
  z-index: 1;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  box-shadow:
    0 0 10px #fff,
    0 0 20px #fff,
    0 0 30px rgba(70, 131, 255, 0.8),
    0 0 40px rgba(70, 131, 255, 0.6),
    0 0 50px rgba(70, 131, 255, 0.4);
  animation: brightStarTwinkle 3s infinite ease-in-out;
}

.star1 {
  width: 3px;
  height: 3px;
  top: 20%;
  left: 10%;
  box-shadow: 0 0 10px 2px rgba(255, 255, 255, 0.8);
  animation-delay: 0s;
}

.star2 {
  width: 2px;
  height: 2px;
  top: 15%;
  left: 35%;
  box-shadow: 0 0 8px 2px rgba(255, 255, 255, 0.7);
  animation-delay: 0.3s;
}

.star3 {
  width: 4px;
  height: 4px;
  top: 25%;
  right: 40%;
  box-shadow: 0 0 12px 3px rgba(255, 255, 255, 0.9);
  animation-delay: 0.7s;
}

.star4 {
  width: 3px;
  height: 3px;
  top: 60%;
  left: 20%;
  box-shadow: 0 0 10px 2px rgba(255, 255, 255, 0.8);
  animation-delay: 1.1s;
}

.star5 {
  width: 3px;
  height: 3px;
  bottom: 20%;
  right: 15%;
  box-shadow: 0 0 10px 2px rgba(255, 255, 255, 0.8);
  animation-delay: 1.5s;
}

/* 明亮星星的闪烁动画 */
@keyframes brightStarTwinkle {
  0%, 100% {
    opacity: 0.3;
    transform: scale(0.8);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
}

/* 彗星 */
.comet {
  position: absolute;
  z-index: 5;
  pointer-events: none;
  opacity: 0;
}

.comet1 {
  top: 15%;
  left: -100px;
  animation: cometMove1 15s infinite ease-out;
  animation-delay: 1s;
}

.comet2 {
  top: 30%;
  left: -100px;
  animation: cometMove2 20s infinite ease-out;
  animation-delay: 8s;
}

.comet3 {
  top: 60%;
  left: -100px;
  animation: cometMove3 12s infinite ease-out;
  animation-delay: 17s;
}

/* 彗星的核心和尾巴 */
.comet-body {
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
  position: relative;
  box-shadow:
    0 0 15px white,
    0 0 30px white,
    0 0 60px white;
}

.comet-tail {
  position: absolute;
  top: 50%;
  right: 3px;
  width: 100px;
  height: 3px;
  background: linear-gradient(to right,
    rgba(255, 255, 255, 1),
    rgba(255, 255, 255, 0.8),
    rgba(255, 255, 255, 0.5),
    transparent);
  transform: translateY(-50%);
  filter: blur(1px);
}

/* 彗星移动动画 */
@keyframes cometMove1 {
  0% {
    opacity: 0;
    transform: translateX(0) translateY(0) rotate(15deg);
  }
  10% {
    opacity: 1;
  }
  40% {
    opacity: 1;
  }
  70% {
    opacity: 0;
    transform: translateX(calc(100vw + 200px)) translateY(100px) rotate(15deg);
  }
  100% {
    opacity: 0;
    transform: translateX(calc(100vw + 200px)) translateY(100px) rotate(15deg);
  }
}

@keyframes cometMove2 {
  0% {
    opacity: 0;
    transform: translateX(0) translateY(0) rotate(25deg);
  }
  10% {
    opacity: 1;
  }
  40% {
    opacity: 1;
  }
  70% {
    opacity: 0;
    transform: translateX(calc(100vw + 250px)) translateY(150px) rotate(25deg);
  }
  100% {
    opacity: 0;
    transform: translateX(calc(100vw + 250px)) translateY(150px) rotate(25deg);
  }
}

@keyframes cometMove3 {
  0% {
    opacity: 0;
    transform: translateX(0) translateY(0) rotate(10deg);
  }
  15% {
    opacity: 1;
  }
  45% {
    opacity: 1;
  }
  75% {
    opacity: 0;
    transform: translateX(calc(100vw + 300px)) translateY(50px) rotate(10deg);
  }
  100% {
    opacity: 0;
    transform: translateX(calc(100vw + 300px)) translateY(50px) rotate(10deg);
  }
}

/* 半月效果元素 */
.floating-element {
  position: absolute;
  border-radius: 50%;
  filter: blur(2px);
  opacity: 0.5;
  z-index: 0;
}

.element-1 {
  width: 150px;
  height: 150px;
  /* 创建半月效果 */
  background: radial-gradient(circle at 30% 50%,
    rgba(255, 253, 230, 0.95) 0%,
    rgba(255, 236, 179, 0.85) 20%,
    rgba(255, 220, 115, 0.7) 40%,
    rgba(255, 205, 0, 0.5) 60%,
    transparent 80%);
  position: absolute;
  top: 5%;
  right: 5%;
  filter: blur(2px);
  box-shadow:
    0 0 30px rgba(255, 215, 115, 0.6),
    0 0 60px rgba(255, 180, 50, 0.3);
  animation: moonGlow 10s infinite ease-in-out;
  overflow: visible;
}

/* 猫咪剪影 */
.element-1::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cpath d='M30,40 C30,30 45,25 50,35 C55,25 70,30 70,40 C70,40 72,20 80,15 C70,25 75,40 75,40 C75,55 65,70 50,70 C35,70 25,55 25,40 C25,40 30,25 20,15 C28,20 30,40 30,40 Z M40,40 C42,38 48,38 50,40 M50,40 C52,38 58,38 60,40 M45,50 L45,55 M55,50 L55,55 M45,60 C45,65 55,65 55,60' fill='%23000' stroke='%23000' stroke-width='1'/%3E%3C/svg%3E");
  background-size: 60px 60px;
  background-repeat: no-repeat;
  background-position: center 5px;
  transform: rotate(10deg);
  top: -10px;
  right: -15px;
  z-index: 2;
}

/* 半月形状 */
.element-1::after {
  content: '';
  position: absolute;
  width: 95px;
  height: 150px;
  background: #000;
  border-radius: 50%;
  top: 0;
  right: -25px;
  box-shadow: 0 0 20px 5px rgba(0, 0, 0, 0.7);
}

/* 月亮特有的光晕动画 */
@keyframes moonGlow {
  0%, 100% {
    box-shadow: 0 0 30px rgba(200, 220, 255, 0.6);
  }
  50% {
    box-shadow: 0 0 50px rgba(200, 220, 255, 0.8);
  }
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  height: 60px;
  background-color: rgba(20, 20, 30, 0.6);
  border-bottom: 1px solid rgba(134, 3, 174, 0.2);
  padding: 0 20px;
  backdrop-filter: blur(5px);
  position: relative;
  z-index: 10;
  box-shadow: 0 0 10px rgba(134, 3, 174, 0.2);
}

.logo {
  display: flex;
  align-items: center;
  width: 200px;
}

.logo-icon {
  font-size: 24px;
  color: #a17fe0;
  margin-right: 10px;
  text-shadow: 0 0 10px rgba(134, 3, 174, 0.5);
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  background: linear-gradient(90deg, #ffffff, #a5b4fc);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 20px rgba(255, 255, 255, 0.2);
}

.search-bar {
  display: flex;
  align-items: center;
  flex: 1;
  max-width: 600px;
  height: 36px;
  border: 1px solid rgba(134, 3, 174, 0.3);
  border-radius: 4px;
  background-color: rgba(30, 30, 50, 0.4);
  padding: 0 10px;
  margin: 0 20px;
}

.search-bar svg {
  color: #a17fe0;
  margin-right: 10px;
}

.search-bar input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
  background: transparent;
  color: #ffffff;
}

.search-bar input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.search-btn {
  background: linear-gradient(135deg, #7c3aed, #a17fe0);
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 6px 15px;
  margin-left: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.search-btn:hover {
  background: linear-gradient(135deg, #8b5cf6, #c084fc);
  box-shadow: 0 0 15px rgba(134, 3, 174, 0.5);
}

.user-info {
  display: flex;
  align-items: center;
  margin-left: auto;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 10px;
  border: 2px solid rgba(134, 3, 174, 0.3);
}

.user-name {
  color: #ffffff;
  margin-right: 10px;
}

.logout-btn {
  background: none;
  border: none;
  color: #ffffff;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  margin: 0;
}

/* 主内容区 */
.main-content {
  display: flex;
  flex: 1;
  position: relative;
  z-index: 5;
  padding: 15px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 900px) {
  .main-content {
    flex-direction: column;
  }
}

@media (max-width: 600px) {
  .header {
    flex-direction: column;
    height: auto;
    padding: 10px;
  }
  
  .logo, .search-bar, .user-info {
    width: 100%;
    margin: 5px 0;
  }
}
</style>
